package com.invest.service;

import com.google.common.collect.Lists;

import com.invest.domain.model.SystemUserDO;
import com.invest.domain.model.SystemUserRolesDO;
import com.invest.repository.SysUserRepository;
import com.invest.utils.type.SystemUserStatusType;
import com.invest.vo.LoginUserVO;
import com.invest.vo.UserHolder;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/3/3 Exp
 */
@Service
public class UserServiceImpl implements com.invest.service.UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SysUserRepository adminRepository;

    @Override
    public LoginUserVO loadUserByUsername(String username) throws AuthenticationException {

            //取得用户信息和角色
        UserHolder userHolder = adminRepository.loadUser(username, true);

        SystemUserDO systemUserDO = userHolder.getSystemUserDO();
        if(systemUserDO == null){
            LOGGER.error(username+"用户不存在");
            throw new BadCredentialsException("用户不存在");
        }

        if(SystemUserStatusType.instanceOf(systemUserDO.getStatus()) != SystemUserStatusType.NORMAL){
            LOGGER.error(username+"已经被冻结不能登录");
            throw new DisabledException(username+"已经被冻结不能登录");
        }

            //转换
        List<SystemUserRolesDO> systemUserRolesDOList = userHolder.getSystemUserRolesDOList();
        Collection<SimpleGrantedAuthority> roles = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(systemUserRolesDOList)) {
            for (SystemUserRolesDO item : systemUserRolesDOList) {
                roles.add(new SimpleGrantedAuthority(item.getRole()));
            }
        }
        LoginUserVO user = new LoginUserVO(systemUserDO.getId(), systemUserDO.getPassword(), roles);
        user.setSystemUserDO(systemUserDO);
        return user;
    }
}
